package com.whh.dota2helper.service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;

import com.google.gson.Gson;
import com.whh.dota2helper.Constant;
import com.whh.dota2helper.R;
import com.whh.dota2helper.model.Ability;
import com.whh.dota2helper.model.Hero;
import com.whh.dota2helper.self.AbstractDBHelper;

public class HeroService extends AbstractDBHelper{
	private Context context;
	private AbilityService abilityService;
	
	public HeroService(Context context){
		this.context = context;
		abilityService = new AbilityService(context);
	}
	
	public void insertAll(){
		try{
			super.open(context);
			InputStreamReader reader = new InputStreamReader(context.getResources().openRawResource(R.raw.heros));  
			BufferedReader br = new BufferedReader(reader);
			String jsonStr = br.readLine();
			db.beginTransaction(); //手动设置开始事务
			while(jsonStr!=null&&!jsonStr.trim().equals("")){
				Hero hero = new Gson().fromJson(jsonStr, Hero.class);
				hero.setLevel(1);
				ContentValues values = new ContentValues();
				values.put("roles", hero.getRoles());
				values.put("type", hero.getType());
				values.put("group_", hero.getGroup());
				values.put("name_cn", hero.getNameCn());
				values.put("name_en", hero.getNameEn());
				values.put("name_short", hero.getNameShort());
				values.put("header_sb", hero.getHeaderSb());
				values.put("header_vert", hero.getHeaderVert());
				values.put("intelligence", hero.getIntelligence());
				values.put("intelligence_increase", hero.getIntelligenceIncrease());
				values.put("agility", hero.getAgility());
				values.put("agility_increase", hero.getAgilityIncrease());
				values.put("strength", hero.getStrength());
				values.put("strength_increase", hero.getStrengthIncrease());
				values.put("attack_min", hero.getAttackMin());
				values.put("attack_max", hero.getAttackMax());
				values.put("attack_type", hero.getAttackType());
				values.put("move_speed", hero.getMoveSpeed());
				values.put("defense", hero.getDefense());
				values.put("sight_range_night", hero.getSightRangeNight());
				values.put("sight_range_day", hero.getSightRangeDay());
				values.put("attack_range", hero.getAttackRange());
				values.put("missile_speed", hero.getMissileSpeed());
				values.put("cast_point", hero.getCastPoint());
				values.put("cast_backswing", hero.getCastBackswing());
				values.put("attack_point", hero.getAttackPoint());
				values.put("attack_backswing", hero.getAttackBackswing());
				values.put("attack_time", hero.getAttackTime());
				values.put("bio", hero.getBio());
				Long uid = db.insert(HeroService.getTableName(), "id", values);
				Log.i(Constant.LOG_TAG, "hero.save:"+uid);
				List<Ability> alist = hero.getAbilities();
				for(int n=0;n<alist.size();n++){
					Ability ability = alist.get(n);
					ability.setHeroId(uid);
					ContentValues abilityValues = new ContentValues();
					abilityValues.put("hero_id", ability.getHeroId());
					abilityValues.put("name", ability.getName());
					abilityValues.put("img", ability.getImg());
					abilityValues.put("desc", ability.getDesc());
					abilityValues.put("mana_cost", ability.getManaCost());
					abilityValues.put("cool_down", ability.getCoolDown());
					abilityValues.put("effect", ability.getEffect());
					abilityValues.put("tips", ability.getTips());
					Long aid = db.insert(AbilityService.getTableName(), "id", abilityValues);
					Log.i(Constant.LOG_TAG, "ability.save:"+aid);
				}
				jsonStr = br.readLine();
			}
			db.setTransactionSuccessful(); //设置事务处理成功，不设置会自动回滚不提交
			db.endTransaction(); //处理完成 
			Log.i(Constant.LOG_TAG,"hero.insertAll");
		}catch(Exception e){
			Log.e(Constant.LOG_TAG,"hero.insertAll:"+e.getMessage());
		}
	}
	
	public Hero getHero(long id){
		super.open(context);
		String selection = "id="+id;
		Cursor cursor = db.query(getTableName(), null, selection, null,null, null, null);
		cursor.moveToFirst();
		Hero hero = null;
		if (!cursor.isAfterLast() && (cursor.getString(0) != null)) {
			hero = new Hero();
			hero.setLevel(1);
			hero.setId(cursor.getLong(0));
			hero.setGroup(cursor.getInt(1));
			hero.setType(cursor.getInt(2));
			hero.setRoles(cursor.getString(3));
			hero.setNameCn(cursor.getString(4));
			hero.setNameEn(cursor.getString(5));
			hero.setNameShort(cursor.getString(6));
			hero.setHeaderSb(cursor.getString(7));
			hero.setHeaderVert(cursor.getString(8));
			hero.setIntelligence(cursor.getInt(9));
			hero.setIntelligenceIncrease(cursor.getDouble(10));
			hero.setAgility(cursor.getInt(11));
			hero.setAgilityIncrease(cursor.getDouble(12));
			hero.setStrength(cursor.getInt(13));
			hero.setStrengthIncrease(cursor.getDouble(14));
			hero.setAttackMin(cursor.getInt(15));
			hero.setAttackMax(cursor.getInt(16));
			hero.setAttackType(cursor.getInt(17));
			hero.setDefense(cursor.getDouble(18));
			hero.setMoveSpeed(cursor.getInt(19));
			hero.setSightRangeNight(cursor.getInt(20));
			hero.setSightRangeDay(cursor.getInt(21));
			hero.setAttackRange(cursor.getInt(22));
			hero.setMissileSpeed(cursor.getInt(23));
			hero.setCastPoint(cursor.getDouble(24));
			hero.setCastBackswing(cursor.getDouble(25));
			hero.setAttackPoint(cursor.getDouble(26));
			hero.setAttackBackswing(cursor.getDouble(27));
			hero.setAttackTime(cursor.getDouble(28));
			hero.setBio(cursor.getString(29));
			List<Ability> abilities = abilityService.getAbilities(id);
			hero.setAbilities(abilities);
		}
		cursor.close();
		super.close();
		Log.i(Constant.LOG_TAG,"hero.getHero:"+hero==null?"null":hero.getNameEn());
		return hero;
	}

	public boolean save(Hero hero) {
		super.open(context);
		ContentValues values = new ContentValues();
		values.put("roles", hero.getRoles());
		values.put("type", hero.getType());
		values.put("group_", hero.getGroup());
		values.put("name_cn", hero.getNameCn());
		values.put("name_en", hero.getNameEn());
		values.put("name_short", hero.getNameShort());
		values.put("header_sb", hero.getHeaderSb());
		values.put("header_vert", hero.getHeaderVert());
		values.put("intelligence", hero.getIntelligence());
		values.put("intelligence_increase", hero.getIntelligenceIncrease());
		values.put("agility", hero.getAgility());
		values.put("agility_increase", hero.getAgilityIncrease());
		values.put("strength", hero.getStrength());
		values.put("strength_increase", hero.getStrengthIncrease());
		values.put("attack_min", hero.getAttackMin());
		values.put("attack_max", hero.getAttackMax());
		values.put("attack_type", hero.getAttackType());
		values.put("move_speed", hero.getMoveSpeed());
		values.put("defense", hero.getDefense());
		values.put("sight_range_night", hero.getSightRangeNight());
		values.put("sight_range_day", hero.getSightRangeDay());
		values.put("attack_range", hero.getAttackRange());
		values.put("missile_speed", hero.getMissileSpeed());
		values.put("cast_point", hero.getCastPoint());
		values.put("cast_backswing", hero.getCastBackswing());
		values.put("attack_point", hero.getAttackPoint());
		values.put("attack_backswing", hero.getAttackBackswing());
		values.put("attack_time", hero.getAttackTime());
		values.put("bio", hero.getBio());
		Long uid = db.insert(getTableName(), "id", values);
		Log.i(Constant.LOG_TAG, "hero.save:"+uid);
		
		List<Ability> alist = hero.getAbilities();
		for(int i=0;i<alist.size();i++){
			Ability a = alist.get(i);
			a.setHeroId(uid);
			abilityService.save(a);
		}
		super.close();
		return uid>0;
	}

	public List<Hero> getAll(int group,int type) {
		super.open(context);
		String selection = null;
		if(group==-1&&type==-1){
			
		}else if(group!=-1 && type!=-1){
			selection = "group_="+group+" and type="+type;
		}else if(group!=-1 && type==-1){
			selection = "group_="+group;
		}else if(group==-1 && type!=-1){
			selection = "type="+type;
		}
		List<Hero> list = new ArrayList<Hero>();
		Cursor cursor = db.query(getTableName(), null, selection, null,null, null, "id ASC");
		cursor.moveToFirst();
		while (!cursor.isAfterLast() && (cursor.getString(0) != null)) {
			Hero hero = new Hero();
			hero.setLevel(1);
			hero.setId(cursor.getLong(0));
			hero.setGroup(cursor.getInt(1));
			hero.setType(cursor.getInt(2));
			hero.setRoles(cursor.getString(3));
			hero.setNameCn(cursor.getString(4));
			hero.setNameEn(cursor.getString(5));
			hero.setNameShort(cursor.getString(6));
			hero.setHeaderSb(cursor.getString(7));
			hero.setHeaderVert(cursor.getString(8));
			hero.setIntelligence(cursor.getInt(9));
			hero.setIntelligenceIncrease(cursor.getDouble(10));
			hero.setAgility(cursor.getInt(11));
			hero.setAgilityIncrease(cursor.getDouble(12));
			hero.setStrength(cursor.getInt(13));
			hero.setStrengthIncrease(cursor.getDouble(14));
			hero.setAttackMin(cursor.getInt(15));
			hero.setAttackMax(cursor.getInt(16));
			hero.setAttackType(cursor.getInt(17));
			hero.setDefense(cursor.getDouble(18));
			hero.setMoveSpeed(cursor.getInt(19));
			hero.setSightRangeNight(cursor.getInt(20));
			hero.setSightRangeDay(cursor.getInt(21));
			hero.setAttackRange(cursor.getInt(22));
			hero.setMissileSpeed(cursor.getInt(23));
			hero.setCastPoint(cursor.getDouble(24));
			hero.setCastBackswing(cursor.getDouble(25));
			hero.setAttackPoint(cursor.getDouble(26));
			hero.setAttackBackswing(cursor.getDouble(27));
			hero.setAttackTime(cursor.getDouble(28));
			hero.setBio(cursor.getString(29));
			list.add(hero);
			cursor.moveToNext();
		}
		cursor.close();
		super.close();
		Log.i(Constant.LOG_TAG,"hero.getAll:"+list.size());
		return list;
	}
	
	public boolean isExist(){
		super.open(context);
		boolean result = false;
		Cursor cursor = db.rawQuery("select count(1) from "+getTableName(),null);
		if (cursor.moveToNext()) {  
            int count = cursor.getInt(0);  
            if(count>0){
            	result = true;  
            }  
        }   
		cursor.close();
		super.close();
		Log.i(Constant.LOG_TAG,"hero.isExist:"+result);
		return result;
	}

	
	public static String getTableName() {
		return "hero";
	}

	public static String getCreateTableSQL() {
		return "CREATE TABLE IF NOT EXISTS " + getTableName() + "("+
				"id INTEGER PRIMARY KEY, " +
				"group_ INTEGER," +
				"type INTEGER, " +
				"roles VARCHAR(100), " +
				"name_cn VARCHAR(50)," +
				"name_en VARCHAR(50)," +
				"name_short VARCHAR(50)," +
				"header_sb VARCHAR(50)," +
				"header_vert VARCHAR(50)," +
				"intelligence INTEGER," +
				"intelligence_increase DECIMAL(10,2)," +
				"agility INTEGER," +
				"agility_increase DECIMAL(10,2)," +
				"strength INTEGER," +
				"strength_increase DECIMAL(10,2)," +
				"attack_min	INTEGER," +
				"attack_max INTEGER," +
				"attack_type INTEGER," +
				"defense DECIMAL(10,2)," +
				"move_speed INTEGER," +
				"sight_range_night INTEGER," +
				"sight_range_day INTEGER," +
				"attack_range INTEGER," +
				"missile_speed INTEGER," +
				"cast_point DECIMAL(10,2)," +
				"cast_backswing DECIMAL(10,2)," +
				"attack_point DECIMAL(10,2)," +
				"attack_backswing DECIMAL(10,2)," +
				"attack_time DECIMAL(10,2)," +
				"bio VARCHAR(2000)" +
				")";
	}
}
